﻿#include "Robot.h"

using namespace Server::MirObjects;

namespace Server::MirEnvir
{

bool Robot::CheckHour = false;
bool Robot::CheckMinute = false;
DateTime Robot::NextCheck;
std::vector<Robot*> Robot::Robots;

    void Robot::SetNextCheck()
    {
        auto next = DateTime::Now;
        next = next.AddSeconds(-next.Second);
        next = next.AddMinutes(1);

        if (!CheckMinute)
        {
            next = next.AddMinutes(-next.Minute);
            next = next.AddHours(1);

            if (!CheckHour)
            {
                next = next.AddHours(-next.Hour);
                next = next.AddDays(1);
            }
        }

        NextCheck = next;
    }

    bool Robot::IsMatch(DateTime date)
    {
        if (Month && date.Month != Month)
        {
            return false;
        }
        if (Day && date.Day != Day)
        {
            return false;
        }
        if (Hour && date.Hour != Hour)
        {
            return false;
        }
        if (Minute && date.Minute != Minute)
        {
            return false;
        }
        if (DayOfWeek && date.DayOfWeek != DayOfWeek)
        {
            return false;
        }

        return true;
    }

    void Robot::Process(NPCScript *script)
    {
        if (NextCheck > DateTime::Now)
        {
            return;
        }

        auto matches = Robots.Where([&] (std::any x)
        {
            x::IsMatch(DateTime::Now);
        });

        for (auto match : *matches)
        {
            script->Call(match->Page);
        }

        SetNextCheck();
    }

    void Robot::AddRobot(const std::string &page)
    {
        Regex *regex = new Regex(R"(\(([0-9#]{1,2}),([0-9#]{1,2}),([0-9#]{1,2}),([0-9#]{1,2}),([^\s]+)\))");
        Match *match = regex->Match(page);

        if (!match->Success)
        {
            delete regex;
            return;
        }

        auto robot = new Robot();
        robot->Page = page;

        int val;
        if (int::TryParse(match->Groups[1]->Value, val))
        {
            robot->Month = std::make_optional(val);
        }
        if (int::TryParse(match->Groups[2]->Value, val))
        {
            robot->Day = val;
        }
        if (int::TryParse(match->Groups[3]->Value, val))
        {
            CheckHour = true;
            robot->Hour = val;
        }
        if (int::TryParse(match->Groups[4]->Value, val))
        {
            CheckMinute = true;
            robot->Minute = val;
        }
        DayOfWeek enumVal;
        if (Enum::TryParse<DayOfWeek>(match->Groups[5]->Value, true, enumVal))
        {
            robot->DayOfWeek = std::make_optional(enumVal);
        }

        Robots.push_back(robot);

//C# TO C++ CONVERTER TODO TASK: A 'delete robot' statement was not added since robot was passed to a method or constructor. Handle memory management manually.
        delete regex;
    }
}
